import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const currentUserId = getUserId(req);
    console.log('currentUserID', currentUserId);
    const query = searchParams.get('q');
    console.log('query', query);
    if (!query || !currentUserId) {
      return NextResponse.json({ error: '请提供查询参数 "q" 和 "userId"' }, { status: 400 });
    }

    // 查找所有和当前用户有关的好友关系
    const relatedFriends = await prisma.friend.findMany({
      where: {
        OR: [
          { userId: currentUserId },
          { friendId: currentUserId }
        ]
      },
      select: {
        userId: true,
        friendId: true
      }
    });

    // 收集所有相关用户ID
    const relatedUserIds = new Set<string>();
    relatedFriends.forEach(f => {
      relatedUserIds.add(f.userId);
      relatedUserIds.add(f.friendId);
    });
    relatedUserIds.add(currentUserId); // 也排除自己

    // 搜索不在相关用户ID里的用户
    const users = await prisma.user.findMany({
      where: {
        username: {
          contains: query,
        },
        id: {
          notIn: Array.from(relatedUserIds)
        }
      },
      select: {
        id: true,
        username: true,
        avatar: true,
      },
      take: 20,
    });

    return NextResponse.json(users);
  } catch (error) {
    console.error('搜索好友失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}